/***************************************************************************
 * Copyright 2012-2013 TXT e-solutions SpA
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * 
 * This work was performed within the IoT_at_Work Project
 * and partially funded by the European Commission's
 * 7th Framework Programme under the contract ICT-257367.
 *
 * Authors:
 *      Salvatore Piccione (TXT e-solutions SpA)
 *
 * Contributors:
 *        Domenico Rotondi (TXT e-solutions SpA)
 **************************************************************************/
package it.txt.ens.client.publisher.impl.util;

import it.txt.ens.client.core.factory.ENSBrokerConnectionParametersFactory;
import it.txt.ens.client.core.factory.ENSClientFactory;
import it.txt.ens.client.impl.BasicENSBrokerConnectionParameters.BasicENSBrokerConnectionParametersFactory;
import it.txt.ens.client.publisher.ENSPublisher;
import it.txt.ens.client.publisher.impl.BasicENSPublisher.BasicENSPublisherFactory;
import it.txt.ens.core.ENSAuthzServiceConnectionParameters;
import it.txt.ens.core.ENSResource;
import it.txt.ens.core.KeystoreParameters;
import it.txt.ens.core.X509CertificateRetrievalParameters;
import it.txt.ens.core.impl.BasicENSAuthzServiceConnectionParameters.BasicENSConnectionParametersFactory;
import it.txt.ens.core.impl.BasicENSResource.BasicENSResourceFactory;
import it.txt.ens.core.impl.BasicKeystoreParameters.BasicKeystoreParametersFactory;
import it.txt.ens.core.impl.BasicX509CertificateRetrievalParameters.BasicX509CertificateRetrievalParametersFactory;
import it.txt.ens.core.util.parser.ENSConnectionParametersDictionaryParser;
import it.txt.ens.core.util.parser.ENSConnectionParametersMapParser;
import it.txt.ens.core.util.parser.ENSResourceDictionaryParser;
import it.txt.ens.core.util.parser.ENSResourceMapParser;
import it.txt.ens.core.util.parser.KeystoreParametersDictionaryParser;
import it.txt.ens.core.util.parser.KeystoreParametersMapParser;
import it.txt.ens.core.util.parser.ParseException;
import it.txt.ens.core.util.parser.X509CertificateRetrievalParametersDictionaryParser;
import it.txt.ens.core.util.parser.X509CertificateRetrievalParametersMapParser;
import it.txt.ens.schema.factory.ENSRequestFactoryException;
import it.txt.ens.schema.factory.ENSResponseFactoryException;
import it.txt.ens.schema.request.factory.ENSAuthorisationRequestFactory;
import it.txt.ens.schema.request.factory.ENSAuthorisationRequestFactoryImpl;
import it.txt.ens.schema.response.factory.ENSAuthorisationResponseFactory;
import it.txt.ens.schema.response.factory.ENSAuthorisationResponseFactoryImpl;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;
import java.util.Properties;

/**
 * This class provides methods to create ENS Publisher instances starting from configuration files or objects.
 * 
 * @author Salvatore Piccione (TXT e-solutions SpA - salvatore.piccione AT txtgroup.com)
 * @author Domenico Rotondi (TXT e-solutions SpA - domenico.rotondi AT txtgroup.com)
 *
 */
public class FactoryUtil {
    
    /**
     * Creates a new ENS Publisher using as configuration properties the ones stored in the file <code>configurationFilePath</code>.
     * 
     * @param configurationFilePath the path in the file system of the configuration file
     * @return an ENS Publisher object
     * @throws IOException
     * @throws IllegalArgumentException
     * @throws ConfigurationException
     * @throws ParseException
     * @throws ENSResponseFactoryException
     * @throws java.text.ParseException
     * @throws ENSRequestFactoryException
     */
    public static ENSPublisher create (String configurationFilePath) throws IOException, IllegalArgumentException, ConfigurationException,
            ParseException, ENSResponseFactoryException, java.text.ParseException, ENSRequestFactoryException {
        File configurationFile = new File (configurationFilePath);
        FileInputStream stream = new FileInputStream(configurationFile);
        Properties configuration = new Properties();
        try {
            configuration.load(stream);
        } finally {
            stream.close();
        }
        return create(configuration);
    }
    
    /**
     * Creates a new ENS Publisher using as configuration properties <code>configuration</code>.
     * 
     * @param configuration the configuration properties
     * @return an ENS Publisher object
     * @throws ConfigurationException
     * @throws IllegalArgumentException
     * @throws ParseException
     * @throws ENSResponseFactoryException
     * @throws java.text.ParseException
     * @throws ENSRequestFactoryException
     */
    public static ENSPublisher create (Properties configuration) throws ConfigurationException, IllegalArgumentException, ParseException,
            ENSResponseFactoryException, java.text.ParseException, ENSRequestFactoryException {
        String subjectID = configuration.getProperty(ENSClientFactory.SUBJECT_ID_KEY);
        if (subjectID == null)
            throw new ConfigurationException(ENSClientFactory.SUBJECT_ID_KEY, "Missing property");

        ENSResource targetResource = ENSResourceDictionaryParser.parse(new BasicENSResourceFactory(),
                configuration);
        
        ENSAuthzServiceConnectionParameters accessRequestBrokerConnParams = ENSConnectionParametersDictionaryParser.parse(
                    new BasicENSConnectionParametersFactory(), configuration);

        KeystoreParameters keystoreParams = KeystoreParametersDictionaryParser.parse(new BasicKeystoreParametersFactory(),
                configuration);
        
        X509CertificateRetrievalParameters certParams = X509CertificateRetrievalParametersDictionaryParser.parse(
                    new BasicX509CertificateRetrievalParametersFactory(),configuration);
        
        String capabilityDirectorySTR = configuration.getProperty(ENSClientFactory.CAPABILITY_DIRECTORY_PATH_KEY);
        if (capabilityDirectorySTR == null)
            throw new ConfigurationException(ENSClientFactory.CAPABILITY_DIRECTORY_PATH_KEY,
                    "Missing property");
        File capabilityDirectory = new File (capabilityDirectorySTR);
        
        ENSBrokerConnectionParametersFactory connParamsFactory = new BasicENSBrokerConnectionParametersFactory();
        
        ENSAuthorisationResponseFactory responseFactory = ENSAuthorisationResponseFactoryImpl.getInstance(
                configuration.getProperty(ENSAuthorisationResponseFactory.SCHEMAS_DIRECTORY_PROP_KEY));

        DateFormat dateFormatter = new SimpleDateFormat(ENSClientFactory.DATE_TIME_FORMAT);
        Date preferredSessionExpiration = dateFormatter.parse(configuration.getProperty(
                ENSClientFactory.PREFERRED_SESSION_EXPIRATION_KEY));
        
        ENSAuthorisationRequestFactory requestFactory = ENSAuthorisationRequestFactoryImpl.getInstance(
                configuration.getProperty(ENSAuthorisationRequestFactory.SCHEMAS_DIRECTORY_PROP_KEY));
        ENSPublisher publisher = new BasicENSPublisherFactory().create(
                subjectID, targetResource, preferredSessionExpiration, accessRequestBrokerConnParams,
                keystoreParams, certParams, capabilityDirectory, requestFactory, responseFactory,
                connParamsFactory);
        
        return publisher;
    }
    
    /**
     * Creates a new ENS Publisher using as configuration properties <code>configuration</code>.
     * 
     * @param configuration the configuration properties
     * @return an ENS Publisher object
     * @throws ConfigurationException
     * @throws IllegalArgumentException
     * @throws ParseException
     * @throws ENSResponseFactoryException
     * @throws java.text.ParseException
     * @throws ENSRequestFactoryException
     */
    public static ENSPublisher create (Map<String, Object> configuration) throws ConfigurationException, IllegalArgumentException, ParseException,
    ENSResponseFactoryException, java.text.ParseException, ENSRequestFactoryException {
        String subjectID = (String) configuration.get(ENSClientFactory.SUBJECT_ID_KEY);
        if (subjectID == null)
            throw new ConfigurationException(ENSClientFactory.SUBJECT_ID_KEY, "Missing property");

        ENSResource targetResource = ENSResourceMapParser.parse(new BasicENSResourceFactory(),
                configuration);
        
        ENSAuthzServiceConnectionParameters accessRequestBrokerConnParams = ENSConnectionParametersMapParser.parse(
                    new BasicENSConnectionParametersFactory(), configuration);

        KeystoreParameters keystoreParams = KeystoreParametersMapParser.parse(new BasicKeystoreParametersFactory(),
                configuration);
        
        X509CertificateRetrievalParameters certParams = X509CertificateRetrievalParametersMapParser.parse(
                    new BasicX509CertificateRetrievalParametersFactory(),configuration);
        
        String capabilityDirectorySTR = (String) configuration.get(ENSClientFactory.CAPABILITY_DIRECTORY_PATH_KEY);
        if (capabilityDirectorySTR == null)
            throw new ConfigurationException(ENSClientFactory.CAPABILITY_DIRECTORY_PATH_KEY,
                    "Missing property");
        File capabilityDirectory = new File (capabilityDirectorySTR);
        
        ENSBrokerConnectionParametersFactory connParamsFactory = new BasicENSBrokerConnectionParametersFactory();
        
        ENSAuthorisationResponseFactory responseFactory = ENSAuthorisationResponseFactoryImpl.getInstance(
                (String) configuration.get(ENSAuthorisationResponseFactory.SCHEMAS_DIRECTORY_PROP_KEY));

        DateFormat dateFormatter = new SimpleDateFormat(ENSClientFactory.DATE_TIME_FORMAT);
        Date preferredSessionExpiration = dateFormatter.parse((String) configuration.get(
                ENSClientFactory.PREFERRED_SESSION_EXPIRATION_KEY));
        
        ENSAuthorisationRequestFactory requestFactory = ENSAuthorisationRequestFactoryImpl.getInstance(
                ENSAuthorisationRequestFactory.SCHEMAS_DIRECTORY_PROP_KEY);
        ENSPublisher publisher = new BasicENSPublisherFactory().create(
                subjectID, targetResource, preferredSessionExpiration, accessRequestBrokerConnParams,
                keystoreParams, certParams, capabilityDirectory, requestFactory, responseFactory,
                connParamsFactory);
        
        return publisher;
    }
}
